<?php

class AccountController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
        // if($this->_helper->flashMessenger->hasMessages()){
        	// $this->view->messages = $this->_helper->FlashMessager->getMessages();
		// }
    }

    public function registerAction()
    {
        // Instantiate the registration form model
		$form = new Application_Form_FormRegister();
		$this->view->formRegister = $form;
		
		// Has the form been submitted?
		if($this->getRequest()->isPost()){
			// If the form data is valid, process it
			if($form->isValid($this->_request->getPost())){
				//es valido
				$dataArray = array(
					'username' => $form->getValue('nombre'),
					'email' => $form->getValue('email'),
					'password' => md5($form->getValue('pwd')),
					'zip' => $form->getValue('codPostal'),
					'created' => date('Y-m-d h:i:s')
				);
				
				$account = new Application_Model_DbTable_Account();
				$account->insert($dataArray);
			}else{
				$this->view->errors = $form->getErrors();
			}
		}
		
		$this->view->formRegister = $form;
        				
    }

    public function loginAction()
    {
        // action body
		/**/
		$form = new Application_Form_FormLogin();
        //Zend_Debug::dump($form);die();
        $session = new Zend_Session_Namespace('Zend_Form_Element_Hash_unique_csrf');

		// $this->_helper->flashMessenger->addMessage('<span class="title">Sys1</span><span class="desc">'.$this->_request->isPost().'</span><span class="exp">0</span>');
		// $this->_helper->flashMessenger->addMessage('<span class="title">Sys2</span><span class="desc">a'.print_r($form->isValid($this->_request->getPost())).'</span><span class="exp">0</span>');

		if ($this->_request->isPost() && $form->isValid($this->_request->getPost())) { echo "pass";
			// Valid
			$db = Zend_Db_Table::getDefaultAdapter();
			$authAdapter = new Zend_Auth_Adapter_DbTable($db);
			
			$authAdapter->setTableName('accounts');
			$authAdapter->setIdentityColumn('email');
			$authAdapter->setCredentialColumn('password');
			//$authAdapter->setCredentialTreatment('MD5(?) and confirmed = 1');
			$authAdapter->setCredentialTreatment('MD5(?)');

			$authAdapter->setIdentity($form->getValue('email'));
			$authAdapter->setCredential($form->getValue('pwd'));

			$auth = Zend_Auth::getInstance();
			$result = $auth->authenticate($authAdapter);

			// Did the user successfully login?
			if ($result->isValid()) {
				$account = new Application_Model_DbTable_Account();
				//$lastLogin = $account->findByEmail($form->getValue('email'));
				//$lastLogin->last_login = date('Y-m-d H:i:s');
				//$lastLogin->save();

				$data = array('last_login'=>date('Y-m-d H:i:s'));
				$where = $account->getAdapter()->quoteInto('email = ?', $form->getValue('email'));
				$account->update($data, $where);
				
				 //echo "logged in";die();
				//Zend_Session::rememberMe(1209600);

				$this->_helper->flashMessenger->addMessage('<span class="title">Logged In</span><span class="desc">Ingresaste exitosamente</span><span class="exp">0</span>');
				$this->_helper->redirector('index', 'index');
			} else {

				// echo "auth failed";
				Zend_Session::forgetMe();
				
				$message = "";
				foreach ($result->getMessages() as $message) {
					$message .= "$m\n";
				}

				// $this->view->errors["form"] = array("Login failed.");
				$this->_helper->flashMessenger->addMessage('<span class="title">Login Error 2</span><span class="desc">Usuario o Password incorrecto. '.$message.'</span><span class="exp">0</span>');
				$this->_helper->redirector('index', 'index');
			}

		} else if (count($form->getErrors('csfr')) > 0) {
			//$this->view->errors = $form->getErrors();
			//$this->view->form = $form;
			
			$message = "";

            $message .= "<p>fERR".print_r($form->getMessages(), true)."</p>";
            $message .= "<p>s-hash: ".print_r($session->hash, true)."</p>";
            $message .= "<p>f-hash: ".$form->getValue('csrf')."</p>";
            $message .= "<p>debug".Zend_Debug::dump($_SESSION)."</p>";
			// echo "Not passing";
			$this->_helper->flashMessenger->addMessage('<span class="title">Login Error</span><span class="desc">'.$message.'</span><span class="exp">0</span>');
			//$this->_helper->redirector('index', 'index');
			
			///get him to the error controller 
			//$this->_forward('csrf-forbidden', 'error');
			//return;
		}
        $this->view->form = $form;
        
    }

    public function logoutAction()
    {
        // action body
		Zend_Auth::getInstance()->clearIdentity();
		$this->_helper->flashMessenger->addMessage('<span class="title">Logged Out</span><span class="desc">Haz cerrado tu sesion</span><span class="exp">0</span>');
		$this->_helper->redirector('index', 'index');
    }


}







